﻿using ReflectionStudio.Core;
using ReflectionStudio.Core.Events;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Xml;
using WPFExcelReport.Helpers;
namespace WPFExcelReport
{
    class JLTGB12Report : BaseReport
    {
        #region ----------------PROPERTIES---------------------------------- 
        private Dictionary<string, object> dicParamater; 
        public DataSet setUI = new DataSet(); 
        string DocType;
       
        string Today
        {
            get
            {
                DateTime now = DateTime.Now;
                return now.Year.ToString() + Right("00" + now.Month.ToString(), 2) + Right("00" + now.Day.ToString(), 2);
            }
        }
        #endregion
        public JLTGB12Report()
            : base()
        {
        }
        public JLTGB12Report(Dictionary<string, object> dicParamater)
            : base(dicParamater)
        {
            DocType = dicParamater["DocType"].ToString().Trim();
            strCompany = dicParamater["Company"].ToString().Trim();
            strExcelFile = dicParamater["ExcelFile"].ToString().Trim();
            if (dicParamater.ContainsKey("ROOTDRIVE"))
            {
                Root = dicParamater["ROOTDRIVE"].ToString();
            }
            else
            {
                Root = "C:\\IntexReport";
            }
        }
        public override void WriteExcelReport(string fileType)
        {
            bool IsFTP = false;
            try
            {

                strExcelFile = @"JLT\JLTProduction.xls";
                Standard = "AB50DOC";
                destfolder = SetFolder(Root, "领纱单"); 
                DataRow row = dsSource.Tables["ABPOS"].Rows[0];
                string KRS = row["ABPAUFKRS"].ToString().Trim();
                string LFD = row["ABPAUFLFD"].ToString().Trim();
                string POS = row["ABPAUFPOS"].ToString().Trim();
                long flfd = 0;
                flfd = System.Convert.ToInt64(LFD);
                string newfilename = KRS + "-" + flfd;
                exAgent.CheckWorkBook(newfilename);
                LocalFile(newfilename);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void FillInEXCEL()
        {
            try
            {
                string value = "";
                DataRow row = null;
                int x = 1, y = 1;
                x = 3; y = 5;
                row = dsSource.Tables["ABKOPF"].Rows[0];
                value = row["ABKAUFKRS"].ToString() + "-" + row["ABKAUFLFD"].ToString();
                exAgent.SetCellValue(x, y, value);
                value = row["ABKKDAUFTNR"].ToString();
                x = 3; y = 14;
                exAgent.SetCellValue(x, y, value);

                x = 3; y = 30;
                exAgent.SetCellValue(x, y, Today);
                if (dsSource.Tables.Contains("LIEFDAT"))
                {
                    if (dsSource.Tables["LIEFDAT"].Rows.Count > 0)
                    {
                        row = dsSource.Tables["LIEFDAT"].Rows[0];
                        value = row["LSNAME1"].ToString().Trim() + row["LSNAME2"].ToString();
                        value = GetGB2312Value(value);
                        x = 4; y = 5;
                        exAgent.SetCellValue(x, y, value);
                        value = row["LSSTRASSE1"].ToString();
                        value = GetGB2312Value(value);
                        x = 5; y = 5;
                        exAgent.SetCellValue(x, y, value);
                    }
                }
                int rownum = -1;

                foreach (DataRow dwABPOS in dsSource.Tables["ABPOS"].Rows)
                {
                    rownum++;
                    string art = dwABPOS["ABPART"].ToString();
                    string var = dwABPOS["ABPVAR"].ToString();
                    string color = dwABPOS["ABPFARBE"].ToString();
                    value = dwABPOS["ABPLIEFDAT"].ToString();

                    x = 4; y = 30;
                    exAgent.SetCellValue(x, y, value);
                    value = dwABPOS["ABPFILLER1"].ToString();
                    x = 8; y = 5;
                    exAgent.SetCellValue(x, y, value);

                    #region=====Technical============
                    var query = from rows in dsSource.Tables["GSDAT"].AsEnumerable()
                                where rows["GSART"].ToString() == art
                                & rows["GSVAR"].ToString() == var
                                select rows;
                    foreach (DataRow rw in query)
                    {
                        if (var.Trim() != "")
                            value = art.Trim() + "/" + var;
                        exAgent.SetCellValue(12 + rownum * 2, 3, value);
                        value = rw["GSGARNBEZ"].ToString();
                        value = GetGB2312Value(value);
                        exAgent.SetCellValue(12 + rownum * 2 + 1, 3, value.Trim());
                    }
                    #endregion

                    #region======color=======
                    query = from rows in dsSource.Tables["GSCOLOR"].AsEnumerable()
                            where rows["GSCART"].ToString() == art
                            & rows["GSCVAR"].ToString() == var
                            & rows["GSCFARBE"].ToString() == color
                            select rows;
                    foreach (DataRow rw in query)
                    {
                        exAgent.SetCellValue(12 + rownum * 2, 19, color.Trim());
                        value = rw["GSCBEZ"].ToString().Trim();
                        value = GetGB2312Value(value);
                        exAgent.SetCellValue(12 + rownum * 2 + 1, 19, value);
                        value = rw["GSCMUFRB"].ToString();
                        value = GetGB2312Value(value).Trim();
                        exAgent.SetCellValue(12 + rownum * 2, 24, value);
                    }
                    #endregion

                    #region=====composition=======
                    query = from rows in dsSource.Tables["GSMATK"].AsEnumerable()
                            where rows["GSMART"].ToString() == art
                            & rows["GSMVAR"].ToString() == var
                            select rows;
                    string composition = "";
                    foreach (DataRow rw in query)
                    {
                        string sg = rw["GSMRBEZ"].ToString().Trim();
                        string bez = rw["GSMRSPZ"].ToString();
                        bez = GetGB2312Value(bez).Trim();
                        double ratio = System.Convert.ToDouble(rw["GSMRANT"].ToString()) * 0.1;
                        composition += ratio + "%" + sg + bez;
                    }
                    exAgent.SetCellValue(12 + rownum * 2, 9, composition);
                    #endregion

                    #region====price=======
                    /*value = dwABPOS["ABPSOLLMENGE6"].ToString();
                    value = System.Math.Round(System.Convert.ToDouble(value) * 0.01, 3).ToString() + "kg";
                    exAgent.SetCellValue(4, 27, value);*/
                    query = from rows in dsSource.Tables["ABPR"].AsEnumerable()
                            where rows["ARAUFKRS"].ToString() == dwABPOS["ABPAUFKRS"].ToString()
                            & rows["ARAUFLFD"].ToString() == dwABPOS["ABPAUFLFD"].ToString()
                            & rows["ARAUFPOS"].ToString() == dwABPOS["ABPAUFPOS"].ToString()
                            select rows;
                    double wert = 0;
                    foreach (DataRow rw in query)
                    {
                        value = rw["ARWERT"].ToString();
                        wert += System.Math.Round(System.Convert.ToDouble(value) * 0.001, 2);
                    }
                    //exAgent.SetCellValue(12 + rownum * 2, 24,  wert + "元/kg");
                    #endregion
                    #region====yarn=========
                    double total = 0;
                    query = from rw in dsSource.Tables["GAAUF"].AsEnumerable()
                            where rw["GAAUFKRS"].ToString() == dwABPOS["ABPAUFKRS"].ToString()
                            & rw["GAAUFLFD"].ToString() == dwABPOS["ABPAUFLFD"].ToString()
                            & rw["GAAUFPOS"].ToString() == dwABPOS["ABPAUFPOS"].ToString()
                            & rw["GASA"].ToString() == "310"
                            select rw;
                    int count = 1;
                    count = query.Count();
                    foreach (DataRow rw in query)
                    {
                        double gakg1 = System.Convert.ToDouble(rw["GAKG1"].ToString()) * 0.01;
                        string gaart = rw["GAART"].ToString();
                        string gavar = rw["GAVAR"].ToString();
                        string gacolor = rw["GAFARBE"].ToString();
                        string yarn = gaart.Trim();
                        if (gavar.Trim() != "")
                            yarn += "/" + gavar.Trim();
                        if (gacolor.Trim() != "")
                        {
                            if (gacolor != "000000")
                            {
                                yarn += "/" + gacolor.Trim();
                            }
                        }
                        if (count > 1)
                        {
                            yarn += ":" + gakg1;
                        }
                        else
                        {
                            yarn = gakg1.ToString();
                        }
                        double ABPEAKG = System.Convert.ToDouble(dwABPOS["ABPEAKG"].ToString()) * 0.01;
                        double ABPEASTK = System.Convert.ToDouble(dwABPOS["ABPEASTK"].ToString()) * 0.01;
                        exAgent.SetCellValue(12 + rownum * 2, 24, yarn);
                        exAgent.SetCellValue(12 + rownum * 2, 27, ABPEAKG);
                        exAgent.SetCellValue(12 + rownum * 2, 30, ABPEASTK);
                        //ABPEAKG ABPEASTK
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
       
        private void FillInGB12()
        {
            try
            {
                string value = "";
                DataRow row = null;
                int x = 1, y = 1;
                x = 3; y = 5;
                string str1 = "", str2 = "", str3 = "";
                row = dsSource.Tables["ABKOPF"].Rows[0];
                value = row["ABKAUFKRS"].ToString() + "-" + row["ABKAUFLFD"].ToString();
                exAgent.SetCellValue(x, y, value); 
                value = row["ABKKDAUFTNR"].ToString();
                x = 3; y = 14;
                exAgent.SetCellValue(x, y, value); 
                x = 3; y = 30;
                Helper.GetDate(ref date, ref year, ref month, ref day);
                Helper.GetSplitDate(ref str1, ref str2, ref str3, date);
                exAgent.SetCellValue(3, 30, str3);
                str1 = row["ABKNEUDAT"].ToString();
                Helper.GetSplitDate(ref str1, ref str2, ref str3, str1);
                exAgent.SetCellValue(4, 30, str3);
 /*
                if (dsSource.Tables.Contains("LIEFDAT"))
                {
                    if (dsSource.Tables["LIEFDAT"].Rows.Count > 0)
                    {
                        row = dsSource.Tables["LIEFDAT"].Rows[0];
                        value = row["LSNAME1"].ToString().Trim() + row["LSNAME2"].ToString();
                        value = GetGB2312Value(value);
                        x = 4; y = 5;
                        exAgent.SetCellValue(x, y, value);
 
                        value = row["LSSTRASSE1"].ToString();
                        value = GetGB2312Value(value);
                        x = 5; y = 5;
                        exAgent.SetCellValue(x, y, value); 
                    }
                }*/
                int rownum = -1;
                string remark = "";
                value = "";
                
                int positions = 0;
                if (!dsSource.Tables.Contains("GAAUF"))
                {
                    return;
                }
                var query = from DataRow ga in dsSource.Tables["GAAUF"].AsEnumerable()
                            where ga["GASA"].ToString() == "713"
                            select ga;
                int count = query.Count();
                string art = "", var = "", color = "";
                double kg = 0, kg3 = 0;
                x = 0;
                string ndate = "";
                int rpl = 2;
                int posx = 12;
                foreach (DataRow ga in query)
                {
                    positions++;
                    art = ga["GAART"].ToString();
                    var = ga["GAVAR"].ToString();
                    color = ga["GAFARBE"].ToString();
            
                    kg = System.Convert.ToDouble(ga["GAKG1"].ToString()) * 0.01;
                    kg3 = System.Convert.ToDouble(ga["GAKG3"].ToString()) * 0.01;
                    if (kg3 == 0)
                    {
                        count--;
                        continue;
                    }
                    ndate = ga["GADATVON"].ToString();
                    Helper.GetSplitDate(ref str1, ref str2, ref str3, ndate);
                    exAgent.SetCellValue(posx, 20, str3);
                    exAgent.SetCellValue(posx, 1,Helper.GetSubRollNum( ga["GAAUFPOS"].ToString()), true);
                    exAgent.SetCellValue(posx, 24, kg, false);
                    #region=====Technical============
                    var query1 = from rows in dsSource.Tables["GSDAT"].AsEnumerable()
                                 where rows["GSART"].ToString() == art
                                 & rows["GSVAR"].ToString() == var
                                 select rows;
                    foreach (DataRow rw in query1)
                    { 
                        value = GetGB2312Value( rw["GSGARNBEZ"].ToString());
                        exAgent.SetCellValue(posx, 3, art + value.Trim());
                    }
                    #endregion
                    #region=====COLOR============
                    if (dsSource.Tables.Contains("GSCOLOR"))
                    {
                        var queryc = from rows in dsSource.Tables["GSCOLOR"].AsEnumerable()
                                     where rows["GSCART"].ToString() == art
                                     & rows["GSCVAR"].ToString() == var
                                     & rows["GSCFARBE"].ToString() == color
                                     select rows;
                        foreach (DataRow rw in queryc)
                        {
                            value = GetGB2312Value(rw["GSCBEZ"].ToString());
                            exAgent.SetCellValue(posx, 16, color.Trim() + value.Trim());
                            if (color.Trim() == "000000")
                            {
                                exAgent.SetCellValue(posx, 16, value.Trim());
                            }
                        }
                    }
                    #endregion  
                    #region=====composition=======
                    if (dsSource.Tables.Contains("GSMATK"))
                    {
                        var query2 = from rows in dsSource.Tables["GSMATK"].AsEnumerable()
                                     where rows["GSMART"].ToString() == art
                                     & rows["GSMVAR"].ToString() == var
                                     select rows;
                        string composition = "";
                        foreach (DataRow rw in query2)
                        {
                            string sg = rw["GSMRBEZ"].ToString().Trim();
                            string bez = rw["GSMRSPZ"].ToString();
                            bez = GetGB2312Value(bez).Trim();
                            double ratio = System.Convert.ToDouble(rw["GSMRANT"].ToString()) * 0.1;
                            composition += ratio + "%" + sg;
                        }
                        exAgent.SetCellValue(posx + 1, 5, composition);
                    }
                    #endregion 
                    #region=====Alloction=======
                    if (dsSource.Tables.Contains("ZUTEI"))
                    {
                        var qzu = from rows in dsSource.Tables["ZUTEI"].AsEnumerable()
                                  where rows["ZUAUFKRS"].ToString() == ga["GAAUFKRS"].ToString()
                                     & rows["ZUAUFLFD"].ToString() == ga["GAAUFLFD"].ToString()
                                    & rows["ZUAUFPOS"].ToString() == ga["GAAUFPOS"].ToString()
                                     & rows["ZUSA"].ToString() == ga["GASA"].ToString()
                                     & rows["ZUPOS"].ToString() == ga["GAPOS"].ToString()
                                  select rows;
                        string filters = "";
                        DataRow[] rx;
                        DataRow dwPartie = null;
                        string info = "";
                        int zucount = qzu.Count();
                        int zupos = 0;
                        foreach (DataRow rw in qzu)
                        {
                            // ZUPARTIEZULO	ZULB ZUEINTKG ZUENTNKG
                            double allocated = System.Convert.ToDouble(rw["ZUEINTKG"].ToString().Trim()) * 0.001;
                            double get = System.Convert.ToDouble(rw["ZUENTNKG"].ToString().Trim()) * 0.001;
                            double TOGET = allocated - get;
                            string sppartie =rw["SELLER"].ToString().Trim()+"-"+rw["ZUSPPART"].ToString().Trim();
                            if (TOGET == 0)
                            {
                                zucount--;
                                continue;
                            }
                            exAgent.SetCellValue(posx + zupos, 27, Helper.GetGB2312Value(sppartie));
                            exAgent.SetCellValue(posx + zupos, 31, rw["GLLP"].ToString().Trim());
                            exAgent.SetCellValue(posx + zupos, 33, TOGET);
                            zupos++;
                            if (zupos > 1
                             && zupos < zucount
                             && zucount > 2)
                            {
                                exAgent.RangeCopy(13, 13, posx + zupos, posx + zupos);
                            }
                        }
                        if (zupos > 2)
                        {
                            posx = posx + zupos-2;
                        }
                    }
                    posx=posx+rpl;
                    #endregion 
                    if (positions < count)
                    {
                        exAgent.RangeCopy(12, 12+rpl-1, posx, posx+rpl-1);
                    }
                }              
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        } 
        
        private string CreateFile(string orderno)
        {
            string filename = "";
            string sheetName = "";
            string filePath = Path.Combine(PathHelper.ApplicationPath, @"Report\JLT\JLTProduction.xls");
            try
            {
                string pwd = "";
                sheetName = orderno;
                if (exAgent == null)
                {
                    exAgent = new ExcelX.ExcelLib.ExcelAgent(dicParamater);
                }
                exAgent.Open(filePath);
                exAgent.Company = strCompany;
                exAgent.strExcelFile = strExcelFile;
                string newfilename = orderno;
                Standard = "AB50GB12";
                List<string> Standards = new List<string>();
                Standards.Add("AB50GB12");
                exAgent.CreateNewSheets(newfilename, Standards, pwd);
                exAgent.SetCurrentSheet("AB50GB12");
                exAgent.RenameSheet("原纱领用");
                FillInGB12();
                filename = exAgent.FileName;
                /*exAgent.SetCurrentSheet("AB50VK35");
                exAgent.RenameSheet("花号用纱");
                FillinVK35();
                exAgent.Save();
                exAgent.SetCurrentSheet("AB50DOC");
                exAgent.RenameSheet("纱线生产单");
                FillInEXCEL();
                 */
                //System.Diagnostics.Process.Start("EXCEL.EXE", localFile);
                exAgent.SetCurrentSheet("原纱领用");
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                exAgent.Save();
                exAgent.Close();
            }
            return filename;
        }

        private void LocalFile(string ordernumer)
        {
            string fileabsname = ordernumer + ".xls";
            string localFile = @"C:\Windows\Temp\" + fileabsname;
            string tempfile = "";
            try
            {
                tempfile = CreateFile(fileabsname);
                localFile =destfolder+"\\" + fileabsname;
                if (System.IO.File.Exists(localFile))
                {
                    System.IO.File.Delete(localFile);
                }
                File.Move(tempfile, localFile);
                System.Diagnostics.Process.Start("EXCEL.EXE", localFile);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                if (File.Exists(tempfile))
                {
                    File.Delete(tempfile);
                }
            }
        }
    }
}